<template>
  <div class="specification-editor">
    <!-- 规格属性管理 -->
    <div class="spec-properties">
      <div v-for="(spec, index) in modelValue" :key="index" class="spec-item">
        <el-input
          v-model="spec.name"
          placeholder="规格名称(如:颜色)"
          style="width: 150px; margin-right: 10px;"
        />
        <el-tag
          v-for="(value, valueIndex) in spec.values"
          :key="valueIndex"
          closable
          @close="removeSpecValue(index, valueIndex)"
        >
          {{ value }}
        </el-tag>
        <el-input
          v-model="newSpecValues[index]"
          placeholder="添加规格值"
          style="width: 120px; margin-left: 10px;"
          @keyup.enter="addSpecValue(index)"
        >
          <template #append>
            <el-button @click="addSpecValue(index)">+</el-button>
          </template>
        </el-input>
        <el-button
          type="danger"
          text
          @click="removeSpec(index)"
        >
          删除
        </el-button>
      </div>
      
      <el-button @click="addNewSpec">添加规格</el-button>
    </div>
    
    <!-- SKU表格 -->
    <div v-if="modelValue.length > 0" class="sku-table">
      <h4>SKU列表</h4>
      <el-table :data="currentSkus" border style="width: 100%">
        <el-table-column
          v-for="spec in modelValue"
          :key="spec.name"
          :label="spec.name"
          :prop="spec.name"
        >
          <template #default="{ row }">
            {{ row.specs[spec.name] }}
          </template>
        </el-table-column>
        
        <el-table-column label="市场价格" width="150">
          <template #default="{ row }">
            <el-input-number
              v-model="row.cost_price"
              :min="0"
              :precision="2"
              size="small"
            />
          </template>
        </el-table-column>

        <el-table-column label="销售价格" width="150">
          <template #default="{ row }">
            <el-input-number
              v-model="row.price"
              :min="0"
              :precision="2"
              size="small"
            />
          </template>
        </el-table-column>
        
        <el-table-column label="库存" width="150">
          <template #default="{ row }">
            <el-input-number
              v-model="row.stock"
              :min="0"
              size="small"
            />
          </template>
        </el-table-column>


        <el-table-column label="虚拟销量" width="150">
          <template #default="{ row }">
            <el-input-number
              v-model="row.virtualSales"
              :min="0"
              size="small"
            />
          </template>
        </el-table-column>

        <el-table-column label="图片" width="150">
          <template #default="{ row }">
            <SingleImageUpload v-model="row.image" :data="{fileType:'image'}" />
          </template>
        </el-table-column>
        
        <!-- <el-table-column label="SKU编码" width="180">
          <template #default="{ row }">
            <el-input
              v-model="row.code"
              placeholder="自动生成"
              size="small"
            />
          </template>
        </el-table-column> -->
      </el-table>

      

    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, defineProps, defineEmits } from 'vue'

interface ProductSpecification {
  name: string
  values: string[]
  skus?: SkuItem[]
}

export interface SkuItem {
  id?: string
  specs: { [key: string]: string }
  cost_price: number
  price: number
  stock: number
  code?: string
  image?: string
  virtualSales?: number,
}


const props = defineProps<{
  modelValue: ProductSpecification[],
  currentSkus: SkuItem[]
}>()

console.log(props);

const currentSkus = ref(props.currentSkus)

const emit = defineEmits(['update:modelValue','change','change2'])

// 用于临时存储新添加的规格值
const newSpecValues = ref<string[]>([])



// 添加新规格
const addNewSpec = () => {
  const newSpecs = [...props.modelValue, { name: '', values: [], skus: [] }]
  emit('change', newSpecs)
  newSpecValues.value.push('')
}

// 删除规格
const removeSpec = (index: number) => {
  const newSpecs = [...props.modelValue]
  newSpecs.splice(index, 1)
  emit('change', newSpecs)
  newSpecValues.value.splice(index, 1)
}

// 添加规格值
const addSpecValue = (specIndex: number) => {
  const value = newSpecValues.value[specIndex]?.trim()
  if (!value) return
  
  const newSpecs = [...props.modelValue]
  if (!newSpecs[specIndex].values.includes(value)) {
    newSpecs[specIndex].values.push(value)
    emit('change', newSpecs)
  }
  newSpecValues.value[specIndex] = ''
}

// 删除规格值
const removeSpecValue = (specIndex: number, valueIndex: number) => {
  const newSpecs = [...props.modelValue]
  newSpecs[specIndex].values.splice(valueIndex, 1)
  emit('change', newSpecs)
}


// 生成所有可能的SKU组合
const generateSkus = (): SkuItem[] => {
  if (props.modelValue.length === 0) return []
  
  // 过滤掉没有名称或值的规格
  const validSpecs = props.modelValue.filter(spec => 
    spec.name.trim() && spec.values.length > 0
  )
  
  if (validSpecs.length === 0) return []
  
  // 生成所有组合
  let combinations: SkuItem[] = [{
    specs: {},
    cost_price: 0,
    price: 0,
    stock: 0,
    code: '',
    virtualSales: 0,
  }]
  
  validSpecs.forEach(spec => {
    const newCombinations: SkuItem[] = []
    combinations.forEach(combination => {
      spec.values.forEach(value => {
        newCombinations.push({
          specs: { ...combination.specs, [spec.name]: value },
          cost_price: combination.cost_price || 0,
          price: combination.price || 0,
          stock: combination.stock || 0,
          code: combination.code || '',
          image: combination.image || '',
          virtualSales: combination.virtualSales || 0
        })
      })
    })
    combinations = newCombinations
  })
  
  return combinations
}



// 监听规格变化，更新SKU
watch(() => props.modelValue, (newVal) => {
  emit('change', newVal,1)
  currentSkus.value = generateSkus()
  console.log(currentSkus);
}, { deep: true })

watch(() => currentSkus, (newVal) => {
  try{
    emit('change2',newVal.value,2)
  }catch (error) {
    console.error(error)
  }
}, { deep: true })

</script>

<style scoped>
.specification-editor {
  margin-top: 15px;
}

.spec-properties {
  margin-bottom: 20px;
}

.spec-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  flex-wrap: wrap;
  gap: 8px;
}

.el-tag {
  margin-right: 5px;
}

.sku-table {
  margin-top: 20px;
}
</style>
